<template>
  <div class="rt-previewer">
    <rt-previewer
      ref="previewer"
      :list="list"
      :options="options"
      @on-index-change="logIndexChange"
    />
  </div>
</template>

<script>
import rtPreviewer from './rtPreviewer';
import { setTimeout } from 'timers';
import Vue from 'vue';
export default {
  name: 'RtImagePreview',
  components: {
    rtPreviewer
  },
  data() {
    return {
      currentIndex: 0,
      opt: {},
      showShare: false,
      showDownload: false,
      list: [],
      options: {
        getThumbBoundsFn(index) {
          // find thumbnail element
          // let thumbnail = document.querySelectorAll('.rt-thumbnail-img > img')[index];
          // get window scroll Y
          let pageYScroll =
            window.pageYOffset || document.documentElement.scrollTop;
          let pageXScroll =
            window.pageXOffset || document.documentElement.scrollLeft;
          // optionally get horizontal scroll
          // get position of element relative to viewport
          // let rect = thumbnail.getBoundingClientRect();

          let clientWidth = document.documentElement.clientWidth;
          let clientHeight = document.documentElement.clientHeight;

          let x = (clientWidth - pageXScroll) / 2;
          let y = (clientHeight - pageYScroll) / 2;
          // w = width
          return {
            x: x,
            y: y,
            w: 0
          };
          // Good guide on how to get element coordinates:
          // http://javascript.info/tutorial/coordinates
        }
      }
    };
  },
  methods: {
    share() {
      let url = this.list[this.currentIndex].msrc;
      this.opt.share(url);
    },
    download() {
      let url = this.list[this.currentIndex].msrc;
      this.opt.download(url);
    },
    logIndexChange(arg) {
      this.currentIndex = arg.currentIndex;
    },
    showImage(params, opt) {
      let tempArr = [];
      let current = 0;

      if (opt) {
        this.opt = opt;
        this.showShare = opt.share;
        this.showDownload = opt.download;
      }
      params.urls.length > 0 &&
        params.urls.map((item, index) => {
          let tem = {};
          if (typeof item === 'string') {
            tem.src = item;
          } else {
            tem = item;
          }
          tempArr.push(tem);
          if (item === params.current) {
            current = index;
          }
        });
      this.currentIndex = current;
      this.list = tempArr;
      setTimeout(() => {
        this.$refs.previewer.show(current);
      }, 100);
    },
    closeImage() {
      setTimeout(() => {
        this.$refs.previewer.close();
      }, 100);
    },
    // 即将废弃
    isShowPreviewImage() {
      return true;
    }
  }
};
</script>

<style scoped></style>
